define([], function () {
	var wsFactory = function (wsAddr, wsOpen, wsClose, wsAsyncCallback, callback) {
		if (!wsAddr) {
			callback();
			return;
		}
		// 如果是https访问，则自动改wss协议
		if (location.protocol.startsWith('https')) {
			if (wsAddr.toLowerCase().startsWith('ws:')) {
				wsAddr = 'wss:' + wsAddr.substring(3);
			}
		}
		$F.log('Elite - initWebsocket', '初始化WebSocket在 ' + wsAddr);
		var intervalId = "";
		const openHeartBeat = function (ws) {
			intervalId = setInterval(function () {
				ws.send('ping')
			}, 10 * 1000)
		}
		try {
			var ws = new WebSocket(wsAddr);
			ws.onmessage = function (e) {
				try {
					if (e.data !== 'pong') {
						var data = JSON.parse(e.data);
						$F.log('Elite - WebSocket', e.data);
						wsAsyncCallback(data);
					} else {
						$F.log('Elite - WebSocket', '心跳消息成功');
					}
				} catch (ex) {
					$F.err('Elite - Websocket', ex);
				}
			};

			ws.onclose = function () {
				$F.log('Elite', "WebSocket连接已关闭");

				if (intervalId) {
					// 在适当的时候，比如在某个事件触发后，关闭定时器
					clearInterval(intervalId);
				}
				wsClose();
				setTimeout(function () {
					wsFactory(wsAddr, wsOpen, wsClose, wsAsyncCallback);
				}, 1000 * 10);
			};

			ws.onerror = function (e) {
				$F.err('Elite', "WebSocket连接错误");

				if (intervalId) {
					// 在适当的时候，比如在某个事件触发后，关闭定时器
					clearInterval(intervalId);
				}
				if ($.isFunction(callback))
					callback();
			};

			ws.onopen = function (e) {
				wsOpen(ws);
				openHeartBeat(ws)
				if ($.isFunction(callback))
					callback();
			};
		} catch (e) {
			console.error(e);
			if ($.isFunction(callback))
				callback();
		}
	}

	return wsFactory;
})

